'use client';

import { createContext, useContext, useState, useEffect } from 'react';
import { ethers } from 'ethers';

import tokenABI from "@/app/abis/token.json";
import herocardABI from "@/app/abis/herocard.json";
import battleABI from "@/app/abis/battle.json";

const WalletContext = createContext();

export function useWallet() {
  return useContext(WalletContext);
}

export function WalletProvider({ children }) {
  const [account, setAccount] = useState('');
  const [provider, setProvider] = useState(null);
  const [isConnecting, setIsConnecting] = useState(false);
  const [error, setError] = useState('');

  //合约实例
  const [tokenContract,setTokenContract] = useState(null);
  const [gameContract,setGameContract] = useState(null);
  const [heroContract,setHeroContract] = useState(null);
  const [battleContract,setBattleContract] = useState(null);

  //用户信息
  const [currentUser,setCurrentUser] = useState('');

  const connectWallet = async () => {
    if (!window.ethereum) {
      setError('请安装MetaMask钱包');
      return;
    }

    try {
      setIsConnecting(true);
      setError('');
      
      // 连接钱包
      const provider = new ethers.BrowserProvider(window.ethereum);
      const accounts = await provider.send('eth_requestAccounts', []);
      const address = accounts[0];
      setAccount(address);
      setProvider(provider);

      // 创建或更新用户
      const response = await fetch('/api/auth/connect', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ address })
      });

      if (!response.ok) {
        throw new Error('创建用户失败');
      }

      //获取用户信息
      const user = await response.json();
      setCurrentUser(user.id.toString());

      //初始化合约
      const tokenAddress = process.env.NEXT_PUBLIC_TOKEN_ADDRESS;
      const herocardAddress = process.env.NEXT_PUBLIC_HEROCARD_ADDRESS;
      const battleAddress = process.env.NEXT_PUBLIC_BATTLE_ADDRESS;

      const tokenContract = new ethers.Contract(tokenAddress, tokenABI, provider);
      const herocardContract = new ethers.Contract(herocardAddress, herocardABI, provider);
      const battleContract = new ethers.Contract(battleAddress, battleABI, provider);

      setTokenContract(tokenContract);
      setHeroContract(herocardContract);
      setBattleContract(battleContract);


    } catch (err) {
      setError('连接钱包失败：' + err.message);
    } finally {
      setIsConnecting(false);
    }
  };

  const disconnectWallet = () => {
    setAccount('');
    setProvider(null);
  };

  useEffect(() => {
    if (window.ethereum) {
      window.ethereum.on('accountsChanged', (accounts) => {
        if (accounts.length > 0) {
          setAccount(accounts[0]);
        } else {
          disconnectWallet();
        }
      });

      window.ethereum.on('chainChanged', () => {
        window.location.reload();
      });
    }

    return () => {
      if (window.ethereum) {
        window.ethereum.removeListener('accountsChanged', () => {});
        window.ethereum.removeListener('chainChanged', () => {});
      }
    };
  }, []);

  return (
    <WalletContext.Provider
      value={{
        account,
        provider,
        isConnecting,
        error,
        connectWallet,
        disconnectWallet,
        tokenContract,
        heroContract,
        battleContract,
        currentUser
      }}
    >
      {children}
    </WalletContext.Provider>
  );
}